package com.TeacherInfoServer.common.service.Impl;

import com.TeacherInfoServer.common.Result;
import com.TeacherInfoServer.exception.JobNumberNotExistException;
import com.TeacherInfoServer.exception.RecordExistException;
import com.TeacherInfoServer.mapper.PostDoctoralMapper;
import com.TeacherInfoServer.pojo.DTO.AddPostDoctoralDTO;
import com.TeacherInfoServer.pojo.DTO.SearchDTO.PostDoctoralSearchDTO;
import com.TeacherInfoServer.pojo.DTO.UpdatePostDoctoralDTO;
import com.TeacherInfoServer.pojo.entity.PostDoctoral;
import com.TeacherInfoServer.pojo.vo.PostDoctoralListVo;
import com.TeacherInfoServer.pojo.vo.PostDoctoralVo;
import com.TeacherInfoServer.common.service.PostDoctoralService;
import com.TeacherInfoServer.common.service.TeacherService;
import com.TeacherInfoServer.utils.HttpServletUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class PostDoctoralServiceImpl extends ServiceImpl<PostDoctoralMapper, PostDoctoral> implements PostDoctoralService {

    @Autowired
    private PostDoctoralMapper postDoctoralMapper;

    @Autowired
    private TeacherService teacherService;

    @Override
    @Transactional
    public Result<Map<String, Integer>> addOne(AddPostDoctoralDTO addPostDoctoralForm) {
        LambdaQueryWrapper<PostDoctoral> wrapper = new LambdaQueryWrapper<>();
        if (postDoctoralMapper.selectOne(wrapper.eq(PostDoctoral::getTeacherId,addPostDoctoralForm.getTeacherId())) == null){
            if (teacherService.getOne(addPostDoctoralForm.getTeacherId()).getData() != null){
                PostDoctoral postDoctoral =
                        new PostDoctoral(null,
                                addPostDoctoralForm.getTeacherId(),
                                addPostDoctoralForm.getResearchUnit(),
                                addPostDoctoralForm.getEntryDate(),
                                addPostDoctoralForm.getExitDate(),1,null);
                Integer record = postDoctoralMapper.insert(postDoctoral);
                Map<String,Integer> map = new HashMap<>();
                map.put("record",record);
                return Result.success(map);
            } else {
                throw new JobNumberNotExistException();
            }
        } else {
            throw new RecordExistException();
        }
    }

    @Override
    @Transactional
    public Result<PostDoctoralListVo> getList(Long pageNumber, Long pageSize) {
        Page<PostDoctoral> page = new Page<>(pageNumber,pageSize);
        List<PostDoctoral> postDoctoralList = postDoctoralMapper.selectPageWithTeacher(page);
        List<PostDoctoralVo> postDoctoralVoList = getPostDoctoralVoList(postDoctoralList);
        PostDoctoralListVo postDoctoralListVo =
                new PostDoctoralListVo(page.getCurrent(),
                        page.getSize(),
                        page.getPages(),
                        page.getTotal(),
                        postDoctoralVoList);
        return Result.success(postDoctoralListVo);
    }

    @Override
    public Map<String,Object> searchPostDoctoralList(PostDoctoralSearchDTO postDoctoralSearchDTO) {
        Page<PostDoctoralVo> page = new Page<>(postDoctoralSearchDTO.getPages(), postDoctoralSearchDTO.getSize());
        postDoctoralMapper.searchPostDoctoralList(page, postDoctoralSearchDTO);
        Map<String, Object> data = new HashMap<>();
        data.put("totals", page.getTotal());
        data.put("currentPages", page.getCurrent());
        data.put("pageNumber", page.getPages());
        data.put("rows", page.getRecords());
        return data;
    }

    @Override
    public void export(HttpServletResponse response, String fileName) throws IOException {
        HttpServletUtil.setExportResponse(response,fileName);
        List<PostDoctoral> postDoctoralList = postDoctoralMapper.selectPageWithTeacher(null);
        List<PostDoctoralVo> postDoctoralVoList = getPostDoctoralVoList(postDoctoralList);
        EasyExcel.write(response.getOutputStream(), PostDoctoralVo.class).excelType(ExcelTypeEnum.XLSX).sheet().doWrite(postDoctoralVoList);

    }


    @Override
    @Transactional
    public Result<Map<String, Integer>> deleteBatch(String[] teacherIds) {
        LambdaQueryWrapper<PostDoctoral> wrapper = new LambdaQueryWrapper<>();
        Integer record = postDoctoralMapper.delete(wrapper.in(PostDoctoral::getTeacherId, Arrays.asList(teacherIds)));
        Map<String, Integer> map = new HashMap<>();
        map.put("record", record);
        return Result.success(map);
    }

    @Override
    @Transactional
    public Result<Map<String, Integer>> updateOne(UpdatePostDoctoralDTO updatePostDoctoralForm) {
        LambdaUpdateWrapper<PostDoctoral> updateWrapper = new LambdaUpdateWrapper<>();
        int record;
        if (teacherService.getOne(updatePostDoctoralForm.getTeacherId()).getData() != null){
            record = postDoctoralMapper.update(null, updateWrapper.eq(PostDoctoral::getId, updatePostDoctoralForm.getId())
                    .set(PostDoctoral::getTeacherId, updatePostDoctoralForm.getTeacherId())
                    .set(PostDoctoral::getResearchUnit, updatePostDoctoralForm.getResearchUnit())
                    .set(PostDoctoral::getEntryDate, updatePostDoctoralForm.getEntryDate())
                    .set(PostDoctoral::getExitDate, updatePostDoctoralForm.getExitDate()));
        } else {
            throw new JobNumberNotExistException();
        }
        LambdaQueryWrapper<PostDoctoral> queryWrapper = new LambdaQueryWrapper<>();
        if (postDoctoralMapper.selectList(queryWrapper.eq(PostDoctoral::getTeacherId,updatePostDoctoralForm.getTeacherId())).size() > 1){
            throw new RecordExistException();
        }
        Map<String, Integer> map = new HashMap<>();
        map.put("record", record);
        return Result.success(map);
    }

    private List<PostDoctoralVo> getPostDoctoralVoList(List<PostDoctoral> postDoctoralList){
        return postDoctoralList.stream()
                .map(postDoctoral -> new PostDoctoralVo(
                        postDoctoral.getId(),
                        postDoctoral.getTeacherId(),
                        postDoctoral.getTeacher().getTeacherName(),
                        postDoctoral.getResearchUnit(),
                        postDoctoral.getEntryDate(),
                        postDoctoral.getExitDate()
                ))
                .collect(Collectors.toList());
    }

}
